<template>
	<view class="main-content">
		<MHeader>{{state.pageName}}</MHeader>
		<scroll-view scroll-y="true" style="height:calc(100% - 180rpx)">
			<!-- 业务员 财务补充信息时不能修改业务员填写的内容 -->
			<view :style="state.myInfo.role.includes(7)&&{pointerEvents:'none'}">
				<item name="组织" sign>
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName" disabled placeholder="请选择" @click.native="choose('ORG_Organizations','F_QUQY_ORGID','FNumber','F_QUQY_ORGName','FNumber','FName')" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName"  placeholder="请选择" />
				</item>
				<item name="养殖户" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_FARMERSName"  placeholder="请选择" @click.native="choose('BD_Customer','F_QUQY_FARMERS','FNumber','F_QUQY_FARMERSName','FNumber','FName',null,['F_QUQY_PHONE','FTEL'])" />
				</item>
				<item name="上苗日期" must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_SEEDDATE"  @click="chooseT('F_QUQY_SEEDDATE')" placeholder="请选择" />
				</item>
				<item name="合同苗数量" must>
					<input class="input" v-model.number="state.info.Data.Model.F_QUQY_HTMQTY" type="number" style="padding-right: 35rpx;" @input="F_QUQY_HTMQTYInput" />
					<text class="symbol">只</text>
				</item>
				<item name="市场苗数量">
					<input class="input" v-model.number="state.info.Data.Model.F_QUQY_SCMQTY" type="number" style="padding-right: 35rpx;" @input="F_QUQY_SCMQTYInput" />
					<text class="symbol">只</text>
				</item>
				<item name="上苗总数量" must>
					<input class="input" disabled v-model.number="state.info.Data.Model.F_QUQY_QTY" type="number" style="padding-right: 35rpx;" />
					<text class="symbol">只</text>
				</item>
				<van-field v-model="state.info.Data.Model.F_QUQY_HTMPRICE" type="number" label="合同苗价" placeholder="请输入" input-align="right" required>
					<template #extra>
						<text class="field-Input-Right-Text">元 / 只</text>
					</template>
				</van-field>
				<van-field v-model="state.info.Data.Model.F_QUQY_HSPRICE" type="number" label="回收价格" placeholder="请输入" input-align="right" required>
					<template #extra>
						<text class="field-Input-Right-Text">元 / 斤</text>
					</template>
				</van-field>
				<van-field v-model="state.info.Data.Model.F_QUQY_SLPRICE" type="number" label="饲料价格" placeholder="请输入" input-align="right" required>
					<template #extra>
						<text class="field-Input-Right-Text">元 / 袋</text>
					</template>
				</van-field>
				<item name="联系电话">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_PHONE"  placeholder="请输入" />
				</item>
				<item name="养殖类型">
					<input class="input" placeholder="请选择" :value="state.info.Data.Model.TypeName"  @click.native="chooseIt([{Id:0,TypeName:'全架'},{Id:1,TypeName:'半架'},{Id:2,TypeName:'地养'},{Id:3,TypeName:'封闭棚'}],'F_QUQY_YZTYPE','TypeName')" />
				</item>
				<van-field v-model="state.info.Data.Model.F_QUQY_MILEAGE" type="number" label="里程(KM)" placeholder="请输入" input-align="right" required>
					<template #extra>
						<text class="field-Input-Right-Text">KM</text>
					</template>
				</van-field>
				<item name="业务员" sign must>
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_YWYName" disabled placeholder="请选择" @click.native="choose('BD_Empinfo','F_QUQY_YWY','FSTAFFNUMBER','F_QUQY_YWYName','FNumber','FName')" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_YWYName" disabled placeholder="请选择" />
				</item>
				<item name="送料车辆" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_LIAOCARName"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataTwo','F_QUQY_LIAOCAR','FNUMBER','F_QUQY_LIAOCARName','FNumber','FName',null,['F_QUQY_LIAOCARTEM','F_QUQY_CarNumber'])" />
				</item>
				<item name="送料车牌号">
					<!-- 实际字段：F_QUQY_LIAOCARN  代替字段：F_QUQY_LIAOCARTEM -->
					<!-- F_QUQY_LIAOCARN 基础资料不需要传，否则会报错 -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_LIAOCARTEM" disabled placeholder="自动带出" />
				</item>
				<item name="养殖地址">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ADDRESS" placeholder="请输入" />
				</item>
				<!-- 				<item name="组织客户">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ORGCUSTName" disabled placeholder="自动带出" />
				</item> -->
			</view>
			<item name="备注">
				<input class="input" v-model="state.info.Data.Model.F_QUQY_REMARK" placeholder="请输入" />
			</item>
			<view>
				<UpLoad ref="upload" must @remove="remove" :disabled="state.myInfo.role.includes(7)"></UpLoad>
			</view>
			<view class="gap"></view>
			<!-- 养殖公司财务专员 -->
			<view v-if="state.myInfo.role.includes(7)">
				<item name="屠宰场" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ABATTOIRName"  placeholder="请选择" @click.native="choose('BD_Customer','F_QUQY_ABATTOIR','FNUMBER','F_QUQY_ABATTOIRName','FNumber','FName',null)" />
				</item>
				<van-field v-model="state.info.Data.Model.F_QUQY_MIAOPRICE" type="number" label="采购苗价" placeholder="请输入" input-align="right">
					<template #extra>
						<text class="field-Input-Right-Text">元 / 只</text>
					</template>
				</van-field>
				<van-field v-model="state.info.Data.Model.F_QUQY_BZJPRICE" type="number" label="保证金" placeholder="请输入" input-align="right">
					<template #extra>
						<text class="field-Input-Right-Text">元 / 只</text>
					</template>
				</van-field>
				<van-field v-model="state.info.Data.Model.F_QUQY_FXPRICE" type="number" label="风险金" placeholder="请输入" input-align="right">
					<template #extra>
						<text class="field-Input-Right-Text">元 / 只</text>
					</template>
				</van-field>
				<van-field v-model="state.info.Data.Model.F_QUQY_SYPRICE" type="number" label="兽药只价" placeholder="请输入" input-align="right">
					<template #extra>
						<text class="field-Input-Right-Text">元 / 只</text>
					</template>
				</van-field>
				<van-field v-model="state.info.Data.Model.F_QUQY_STANDARD" type="number" label="标准用料" placeholder="请输入" input-align="right">
					<template #extra>
						<text class="field-Input-Right-Text">斤 / 只</text>
					</template>
				</van-field>
				<item name="苗供应商" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_SUPPLIERName"  placeholder="请选择" @click.native="choose('BD_Supplier','F_QUQY_SUPPLIER','FNUMBER','F_QUQY_SUPPLIERName','FNumber','FName')" />
				</item>
				<item name="送苗车辆" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_MIAOCARName"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataTwo','F_QUQY_MIAOCAR','FNUMBER','F_QUQY_MIAOCARName','FNumber','FName',null,['F_QUQY_MIAOCARTEM','F_QUQY_CarNumber'])" />
				</item>
				<item name="送苗车牌号">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_MIAOCARTEM" disabled placeholder="自动带出" />
				</item>
				<item name="技术员" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_JSYName"  placeholder="请选择" @click.native="choose('BD_Empinfo','F_QUQY_JSY','FSTAFFNUMBER','F_QUQY_JSYName','FNumber','FName')" />
				</item>
				<van-field v-model="state.info.Data.Model.F_QUQY_TZBJ" type="number" label="屠宰保价" placeholder="请输入" input-align="right"/>
				<item name="经销模式">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_JXTYPEName"  @click="chooseIt(state.F_QUQY_JXTYPEList,'F_QUQY_JXTYPE','F_QUQY_JXTYPEName')" placeholder="请选择" />
				</item>
				<item name="经销商" sign v-if="state.info.Data.Model.F_QUQY_JXTYPE==2">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_JXSName"  placeholder="请选择" @click.native="choose('BD_Customer','F_QUQY_JXS','FNUMBER','F_QUQY_JXSName','FNumber','FName',null,['F_QUQY_PHONE','FTEL'])" />
				</item>
				<!-- 				<MHeader hidTag>
					<van-icon name="cluster" color="#1989fa" style="margin-right: 10rpx" />
					明细
					<template #right>
						<van-icon name="add-o" size="20" @click="appendItem" />
					</template>
				</MHeader>
				<view style="padding-bottom: 10rpx">
					<view class="card" v-for="(item, index) in state.info.Data.Model.FEntity">
						<view class="card-index">{{ index + 1 }}</view>
						<item name="料" @longpress="longpress(item, index)">
							<input class="input" v-model="item.F_QUQY_MATERIALName" disabled placeholder="请选择" @click.native="choose('BD_MATERIAL','F_QUQY_MATERIAL','FNUMBER','F_QUQY_MATERIALName','FNumber','FName',101190,null,item)" />
						</item>
						<item name="合同价">
							<input class="input" v-model="item.F_QUQY_HTPRICE" type="number" style="padding-right: 35rpx;" />
							<text class="symbol">元</text>
						</item>
					</view>
				</view> -->
			</view>

		</scroll-view>
		<view class="btns">
			<van-button type="primary" size="small" @click="save(null)">保 存</van-button>
		</view>
	</view>
	<ChooseTime ref="chooseTime" />
	<ChooseItem ref="chooseItem" />
	<Loading v-if="state.loading" />
</template>

<script setup>
	// 业务员：新增（保存）提交 撤销   财务：审核 反审核
	// QUQY_SeedPlan
	import moment from 'moment'
	import { reactive, getCurrentInstance, ref, watch, nextTick } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { checkForm, msg, confirm, base64ToUint8Array } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	import axios from 'axios'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		loading: true,
		info: {
			FormId: 'QUQY_SeedPlan',
			Data: {
				Model: {
					// FID: 0,
					// FBillNo: '',
					// F_QUQY_SMSTATE: '', // 上苗状态
					// FDocumentStatus: '', // 单据状态
					F_QUQY_ORGID: {
						FNumber: null
					},
					F_QUQY_FARMERS: {
						FNumber: null
					},
					F_QUQY_YWY: {
						FSTAFFNUMBER: null
					},
					F_QUQY_LIAOCAR: {
						FNUMBER: null
					},
					F_QUQY_ORGCUST: {
						FNUMBER: null
					},
					TypeName: '全架',
					F_QUQY_YZTYPE: 0,
					FEntity: [],
					F_QUQY_FJID: '',
					F_QUQY_JXTYPEName: '普通模式',
					F_QUQY_JXTYPE: 1
				}
			}
		},
		// 财务需要填写的
		Model2: {
			F_QUQY_ABATTOIR: {
				FNUMBER: null
			},
			F_QUQY_SUPPLIER: {
				FNUMBER: null
			},
			F_QUQY_MIAOCAR: {
				FNUMBER: null
			},
			F_QUQY_JSY: {
				FSTAFFNUMBER: null
			},
			F_QUQY_JXS: {
				FNUMBER: null
			}
		},
		// 业务员必填
		rules: {
			F_QUQY_FARMERS: '请选择养殖户！',
			F_QUQY_SEEDDATE: '请选择上苗日期！',
			F_QUQY_HTMQTY: '请输入合同苗数量！',
			F_QUQY_QTY: '请输入上苗数量！',
			F_QUQY_YWYName: '请选择业务员！',
			F_QUQY_HTMPRICE: '请输入合同苗价',
			F_QUQY_LIAOCARName: '请选择送料车辆！',
			
			F_QUQY_HSPRICE: '请输入回收价格',
			F_QUQY_SLPRICE: '请输入饲料价格'
		},
		// 财务必填
		rules2: {
			F_QUQY_ABATTOIRName: '请选择屠宰场！',
			F_QUQY_SUPPLIERName: '请选择苗供应商！',
			F_QUQY_MIAOCARName: '请选择送苗车辆！',
			F_QUQY_JSYName: '请选择技术员！',
		},
		pageName: "上苗计划新增",
		myInfo: null,
		yzType: {
			0: '全架',
			1: '半架',
			2: '地养',
			3: '封闭棚'
		},
		F_QUQY_JXTYPEList: [
			{ Id: 1, F_QUQY_JXTYPEName: '普通模式' },
			{ Id: 2, F_QUQY_JXTYPEName: '经销商模式' },
		],
		curOrgId: null,
		isFirstIn: false
	})

	watch([() => state.info.Data.Model.F_QUQY_JXTYPE], ([F_QUQY_JXTYPE]) => {
		state.info.Data.Model.F_QUQY_JXTYPEName = state.F_QUQY_JXTYPEList.filter(it => it.Id == F_QUQY_JXTYPE)[0].F_QUQY_JXTYPEName
		if(state.isFirstIn == true) return
		if (F_QUQY_JXTYPE == 1) {
			state.info.Data.Model.F_QUQY_JXS = null
			state.info.Data.Model.F_QUQY_JXSName = null
		}
		if (F_QUQY_JXTYPE == 2) {
			state.info.Data.Model.F_QUQY_JXS = {
				FNUMBER: null
			}
			state.info.Data.Model.F_QUQY_JXSName = null
			console.log(111)
		}
	})
	
	const change2 = (item,index,val) =>{
		console.log(val.detail.value)
		if( Number.isFinite(val.detail.value/1)){
		}else{
			state.info.Data.Model.F_QUQY_HTMPRICE= 0
			uni.showToast( {title:"含税单价应为数字",icon:"none"} )
		}
	}

	const chooseTime = ref(null)
	const chooseT = (fieldName) => {
		chooseTime.value.start(state.info.Data.Model, fieldName)
	}

	const F_QUQY_HTMQTYInput = (e) => {
		if (state.info.Data.Model.F_QUQY_SCMQTY) {
			state.info.Data.Model.F_QUQY_QTY = Number(state.info.Data.Model.F_QUQY_SCMQTY) + Number(e.detail.value)
		}
	}

	const F_QUQY_SCMQTYInput = (e) => {
		if (state.info.Data.Model.F_QUQY_HTMQTY) {
			state.info.Data.Model.F_QUQY_QTY = Number(state.info.Data.Model.F_QUQY_HTMQTY) + Number(e.detail.value)
		}
	}

	// 不好，参数太多 -。-
	// 1.组织控制（使用组织为当前选择的组织）：养殖户、司机
	// 2.业务员、技术员要审核过的
	const choose = (FormId, Field, FieldSon, FieldName, IdKey, IdKeyName, Group, BringOther, row) => {
		// 🐟 选择组织前
		if (Field == 'F_QUQY_ORGID') {

		}

		// 🐟 1
		let mustHasOrg = ['F_QUQY_FARMERS', 'F_QUQY_ABATTOIR', 'F_QUQY_SUPPLIER', 'F_QUQY_MATERIAL']
		if (mustHasOrg.includes(Field)) {
			if (!state.info.Data.Model.F_QUQY_ORGName) return msg('请先选择组织！')
		}

		let FR = []
		// 选苗供应商 组织过滤
		if (Field == 'F_QUQY_SUPPLIER' || Field == 'F_QUQY_MATERIAL') {
			FR = [{ Left: "(", FieldName: "FUseOrgId", Compare: "=", Value: state.curOrgId, Right: ")", Logic: "and" }]
		}

		if (Field == 'F_QUQY_ABATTOIR') {
			FR = [{ Left: "(", FieldName: "F_QUQY_YTTYPE", Compare: "=", Value: 2, Right: ")", Logic: "and" }]
		}

		uni.navigateTo({
			url: `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择&R=3`,
			success: res => { res.eventChannel.emit('fun', [fun, null, FR]) }
		})

		// 回调方法
		let fun = (list) => {
			if (Field == 'F_QUQY_MATERIAL') {
				// 🍕 饲料
				// 🍕 子集里的
				row[Field][FieldSon] = list[0][IdKey]
				row[FieldName] = list[0][IdKeyName]
			} else {
				state.info.Data.Model[Field][FieldSon] = list[0][IdKey]
				state.info.Data.Model[FieldName] = list[0][IdKeyName]
				if (BringOther) {
					state.info.Data.Model[BringOther[0]] = list[0][BringOther[1]]?.trim()
				}
			}

			// 🐟 选择组织后
			if (Field == 'F_QUQY_ORGID') {
				// 🍕 查询并带出字段：客户组织（使用组织为当前组织并且名称和当前组织名称相同的客户）
				kdApis.formQuery({
					data: {
						FormId: 'BD_Customer',
						FieldKeys: 'FName,FNUMBER,FUseOrgId',
						FilterString: [{ "Left": "(", "FieldName": "FName", "Compare": "=", "Value": list[0].FName, "Right": ")", "Logic": "and" }, { "Left": "(", "FieldName": "FUseOrgId", "Compare": "=", "Value": list[0].FOrgID, "Right": ")", "Logic": "and" }]
					}
				}).then(res => {
					if (res && res.length) {
						state.info.Data.Model.F_QUQY_ORGCUST.FNUMBER = res[0].FNUMBER
						state.info.Data.Model.F_QUQY_ORGCUSTName = res[0].FName
					}
				})
				// 🍕 初始化 养殖户等字段及其带出的字段
				for (let key in state.info.Data.Model) {
					let value = state.info.Data.Model[key]
					if (mustHasOrg.includes(key) && value) {
						if (typeof(value) === 'object') {
							for (let k in value) { value[k] = null }
							state.info.Data.Model[`${key}Name`] = null
							if (state.info.Data.Model[`${key}TEM`]) state.info.Data.Model[`${key}TEM`] = null // 带出的字段
						} else {
							value = null
						}
					}
				}
				// 🍕 初始化联系方式
				state.info.Data.Model.F_QUQY_PHONE = null
				// 🍕 初始化 以组织为前提的子集里的字段
				if (state.info.Data.Model.FEntity.length) {
					for (let it of state.info.Data.Model.FEntity) {
						it.F_QUQY_MATERIALName = null
						it.F_QUQY_MATERIAL = {
							FNUMBER: null
						}
					}
				}
			}
		}
	}

	const chooseItem = ref(null)
	const chooseIt = async (list, field, fieldName) => {
		chooseItem.value.start(state.info.Data.Model, list, field, fieldName)
	}

	const appendItem = () => {
		let obj = {
			F_QUQY_MATERIAL: {
				FNUMBER: null
			},
			F_QUQY_HTPRICE: null
		}
		state.info.Data.Model.FEntity.push(obj)
	}


	const save = async (FId) => {
		console.log(state.info.Data.Model)
		await checkForm(state.info.Data.Model, state.rules, true, true)
		
		
		if( !Number.isFinite(state.info.Data.Model.F_QUQY_HTMPRICE/1)){
			uni.showToast( {title:"合同苗价应填写数字",icon:"none"} )
			return
		}
		if( !Number.isFinite(state.info.Data.Model.F_QUQY_HSPRICE/1)){
			uni.showToast( {title:"回收价格应填写数字",icon:"none"} )
			return
		}
		if( !Number.isFinite(state.info.Data.Model.F_QUQY_SLPRICE/1)){
			uni.showToast( {title:"饲料价格应填写数字",icon:"none"} )
			return
		}
		// F_QUQY_HTMPRICE 合同苗价  F_QUQY_HSPRICE 回收价格 F_QUQY_SLPRICE 饲料价格
		// return
		
		if (state.myInfo.role.includes(7) && state.info.Data.Model.F_QUQY_JXTYPE == 2 && !state.info.Data.Model.F_QUQY_JXS.FNUMBER) return msg('请选择经销商！')
		if (state.info.Data.Model.F_QUQY_JXTYPE == 1) {
			state.info.Data.Model.F_QUQY_JXS = null
			state.info.Data.Model.F_QUQY_JXSName = null
		}

		if (upload.value.data.fileList.length == 0 && JSON.stringify(upload.value.data.fileListLarge) == '{}') return msg('请上传附件！')
		if (state.myInfo.role.includes(7)) await checkForm(state.info.Data.Model, state.rules2)
		if (FId) {
			// 保存附件后
			state.info.Data.Model.FId = FId
		} else {
			// 保存 如果是编辑保存
			if (state.info.Data.Model.FId) return upLoadFile({ InterId: state.info.Data.Model.FId, BillNO: state.info.Data.Model.BillNo })
		}
		// if(!this.info.F_QUQY_FJID) return msg('请上传附件！')
		kdApis.formSave(state.info).then(res => {
			if (res) {
				if (!FId) {
					upLoadFile({ InterId: res.Result.Id, BillNO: res.Result.Number })
				} else {
					msg('保存成功！')
					setTimeout(() => {
						uni.navigateBack()
					}, 300)
				}
			}
		})
	}

	const upload = ref(null)

	const upLoadFile = async ({ InterId, BillNO }) => {
		if (upload.value.data.reUp) {
			let Ids = state.info.Data.Model.F_QUQY_FJID.split(',').filter(it => it.trim())
			let requests = []
			upload.value.data.fileList.forEach(it => {
				it.FormId = 'QUQY_SeedPlan'
				it.InterId = InterId
				it.BillNO = BillNO
				if (!it.Id) requests.push(kdApis.fileUpLoad({ data: it }))
			})
			let x = await axios.all(requests).then(res => {
				if (res) {
					Ids = res.filter(it => it.Result.ResponseStatus.SuccessEntitys[0]).map(it => it.Result.ResponseStatus.SuccessEntitys[0].Id).concat(Ids)
				}
			})

			let obj = upload.value.data.fileListLarge
			if (Object.keys(obj).length !== 0) {
				for (let key in obj) {
					let value = obj[key] // Array
					let result = await kdApis.fileUpLoad({ data: { ...value[0], FormId: 'QUQY_SeedPlan', InterId, BillNO } })
					for (let [i, val] of value.entries()) {
						if (i) {
							let resu = await kdApis.fileUpLoad({ data: { ...val, FormId: 'QUQY_SeedPlan', InterId, BillNO, FileId: result.Result.FileId } })
							if (resu && resu.Result.ResponseStatus.SuccessEntitys[0]) {
								Ids.push(resu.Result.ResponseStatus.SuccessEntitys[0].Id)
							}
						}
					}
				}
			}

			state.info.Data.Model.F_QUQY_FJID = Ids.join(',')
			save(InterId)
		} else {
			msg('保存成功！')
			save(InterId)
		}
	}

	const remove = (Id) => {
		if (state.info.Data.Model.F_QUQY_FJID) {
			let arr = state.info.Data.Model.F_QUQY_FJID.split(',')
			let index = arr.indexOf(Id)
			if (index > -1) arr.splice(index, 1)
			state.info.Data.Model.F_QUQY_FJID = arr.join(',')
		}
	}

	function mergeUint8Arrays(arrays) {
		const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
		const mergedArray = new Uint8Array(totalLength);
		let offset = 0;

		for (const arr of arrays) {
			mergedArray.set(arr, offset);
			offset += arr.length;
		}
		return mergedArray;
	}

	const getFile = async (res, str, FileId, StartIndex, fun) => {
		if (res.Result.IsLast == true) {
			fun(str)
		} else {
			let result = await kdApis.fileDownLoad({ data: { FileId: FileId, StartIndex } })
			if (result) {
				let Uint8Array = base64ToUint8Array(result.Result.FilePart)
				let mx = mergeUint8Arrays([str, Uint8Array])
				getFile(result, mx, FileId, result.Result.StartIndex, fun)
			}
		}
	}

	const getFiles = async (Id) => {
		let fjs = state.info.Data.Model.F_QUQY_FJID.split(',').filter(it => it.trim())
		if (fjs.length == 0) return
		let files = []
		let files2 = []
		for (let it of fjs) {
			let fileInfo = await kdApis.formView({ formId: 'BOS_Attachment', data: { Id: it } })
			if (fileInfo) {
				let fileDetais = await kdApis.fileDownLoad({ data: { FileId: fileInfo.FileId, StartIndex: 0 } })
				if (fileDetais) {
					if (fileDetais.Result.IsLast == false) {
						let fun = (val) => {
							var blob = new Blob([val], { type: `image/${fileInfo.ExtName.slice(1)}` })
							let src = URL.createObjectURL(blob)
							files.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
							files2.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
						}
						getFile(fileDetais, base64ToUint8Array(fileDetais.Result.FilePart), fileInfo.FileId, fileDetais.Result.StartIndex, fun)
					} else {
						let Uint8Array = base64ToUint8Array(fileDetais.Result.FilePart)
						var blob = new Blob([Uint8Array], { type: `image/${fileInfo.ExtName.slice(1)}` })
						let src = URL.createObjectURL(blob)
						files.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
						files2.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
					}
				}

			}
		}
		upload.value.data.fileList2 = files2
		upload.value.data.fileList = files
	}

	const getDetails = (Id) => {
		state.isFirstIn = true
		return kdApis.formView({
			formId: 'QUQY_SeedPlan',
			data: { Id }
		}).then(res => {
			if (res) {
				// 🍕 业务员部分
				let obj = {
					BillNo: res.BillNo,
					FId: res.Id,
					F_QUQY_ORGID: {
						FNumber: res.F_QUQY_ORGID?.Number
					},
					F_QUQY_ORGName: res.F_QUQY_ORGID?.Name[0].Value,
					F_QUQY_FARMERS: {
						FNumber: res.F_QUQY_FARMERS?.Number
					},
					F_QUQY_FARMERSName: res.F_QUQY_FARMERS?.Name[0].Value,
					F_QUQY_SEEDDATE: moment(res.F_QUQY_SEEDDATE).format('YYYY-MM-DD'),
					F_QUQY_QTY: res.F_QUQY_QTY,
					F_QUQY_HTMQTY: res.F_QUQY_HTMQTY,
					F_QUQY_SCMQTY: res.F_QUQY_SCMQTY,
					F_QUQY_HTMPRICE: res.F_QUQY_HTMPRICE,
					F_QUQY_HSPRICE: res.F_QUQY_HSPRICE,
					F_QUQY_PHONE: res.F_QUQY_PHONE,
					F_QUQY_YZTYPE: res.F_QUQY_YZTYPE,
					TypeName: state.yzType[res.F_QUQY_YZTYPE],
					F_QUQY_MILEAGE: res.F_QUQY_MILEAGE,
					F_QUQY_YWY: {
						FSTAFFNUMBER: res.F_QUQY_YWY?.FStaffNumber
					},
					F_QUQY_YWYName: res.F_QUQY_YWY?.Name[0].Value,
					F_QUQY_LIAOCAR: {
						FNumber: res.F_QUQY_LIAOCAR?.Number
					},
					F_QUQY_SLPRICE: res.F_QUQY_SLPRICE,
					F_QUQY_LIAOCARName: res.F_QUQY_LIAOCAR?.Name[0].Value,
					F_QUQY_LIAOCARTEM: res.F_QUQY_LIAOCAR?.F_QUQY_CarNumber,
					F_QUQY_ADDRESS: res.F_QUQY_ADDRESS,
					F_QUQY_ORGCUST: {
						FNumber: res.F_QUQY_ORGCUST?.Number
					},
					F_QUQY_ORGCUSTName: res.F_QUQY_ORGCUST?.Name[0].Value,
					F_QUQY_REMARK: res.F_QUQY_REMARK,
					F_QUQY_FJID: res.F_QUQY_FJID
				}
				// 🍕 财务部分
				state.curOrgId = res.F_QUQY_ORGID_Id
				let obj2 = {
					F_QUQY_ABATTOIR: {
						FNumber: res.F_QUQY_ABATTOIR?.Number
					},
					F_QUQY_ABATTOIRName: res.F_QUQY_ABATTOIR?.Name[0].Value,
					F_QUQY_MIAOPRICE: res.F_QUQY_MIAOPRICE || null,
					F_QUQY_BZJPRICE: res.F_QUQY_BZJPRICE || null,
					F_QUQY_FXPRICE: res.F_QUQY_FXPRICE || null,
					F_QUQY_SYPRICE: res.F_QUQY_SYPRICE || null,
					// F_QUQY_SLPRICE: res.F_QUQY_SLPRICE || null,
					F_QUQY_STANDARD: res.F_QUQY_STANDARD || null,
					F_QUQY_SUPPLIER: {
						FNumber: res.F_QUQY_SUPPLIER?.Number
					},
					F_QUQY_SUPPLIERName: res.F_QUQY_SUPPLIER?.Name[0].Value,
					F_QUQY_MIAOCAR: {
						FNumber: res.F_QUQY_MIAOCAR?.Number
					},
					F_QUQY_MIAOCARName: res.F_QUQY_MIAOCAR?.Name[0].Value,
					F_QUQY_MIAOCARTEM: res.F_QUQY_MIAOCAR?.F_QUQY_CarNumber,
					F_QUQY_JSY: {
						FSTAFFNUMBER: res.F_QUQY_JSY?.FStaffNumber
					},
					F_QUQY_JSYName: res.F_QUQY_JSY?.Name[0].Value,
					F_QUQY_JXS: {
						FNUMBER: res.F_QUQY_JXS?.Number
					},
					F_QUQY_JXTYPE: res.F_QUQY_JXTYPE,
					F_QUQY_JXSName: res.F_QUQY_JXS?.Name[0].Value,
					F_QUQY_TZBJ: res.F_QUQY_TZBJ || null,
					FEntity: res.QUQY_SeedPlanEntry.map(it => {
						return {
							F_QUQY_MATERIAL: {
								FNUMBER: it.F_QUQY_MATERIAL?.Number
							},
							F_QUQY_MATERIALName: it.F_QUQY_MATERIAL?.Name[0].Value,
							F_QUQY_HTPRICE: it.F_QUQY_HTPRICE || null
						}
					})
				}

				if (res.F_QUQY_JXTYPE == 1) {
					obj2.F_QUQY_JXS = null
					obj2.F_QUQY_JXSName = null
				}

				// 🍕 如果没有屠宰场信息就置空财务信息；此时为业务员编辑单据
				if (!obj2.F_QUQY_ABATTOIRName) {
					obj2 = {}
					state.info.Data.Model.F_QUQY_JXS = null
					state.info.Data.Model.F_QUQY_JXSName = null
				}
				Object.assign(state.info.Data.Model, obj, obj2)
				getFiles(Id)
				state.loading = false
				setTimeout(()=>{
					state.isFirstIn = false
				},1000)
			}
		})
	}

	const longpress = (item, index) => {
		let msg = item.F_QUQY_MATERIALName ? `请确认删除 [ ${item.F_QUQY_MATERIALName} ] ？` : '请确认删除 ？'
		confirm(msg).then(() => {
			state.info.Data.Model.FEntity.splice(index, 1)
		}).catch(() => {})
	}

	onLoad(async (query) => {
		if (query.Id) {
			state.pageName = "上苗计划编辑"
			getDetails(query.Id)
		} else {
			state.loading = false
			// 🍕 上苗日期默认为当前日期 
			state.info.Data.Model.F_QUQY_SEEDDATE = moment(new Date()).format('YYYY-MM-DD')
			// 🍕 业务员默认当前人
			let memberInfo = uni.getStorageSync('memberInfo')
			state.info.Data.Model.F_QUQY_YWY = {
				FSTAFFNUMBER: memberInfo.Number
			}
			state.info.Data.Model.F_QUQY_YWYName = memberInfo.Name[0].Value
			// 🍕 组织默认当前人组织 F_QUQY_ORGID
			state.info.Data.Model.F_QUQY_ORGID = {
				FNumber: memberInfo.F_QUQY_COMPANY.Number
			}
			state.info.Data.Model.F_QUQY_ORGName = memberInfo.F_QUQY_COMPANY.Name[0].Value

			state.curOrgId = memberInfo.F_QUQY_COMPANY_Id
			// 🍕 查询并带出字段：客户组织（使用组织为当前组织并且名称和当前组织名称相同的客户）
			kdApis.formQuery({
				data: {
					FormId: 'BD_Customer',
					FieldKeys: 'FName,FNUMBER,FUseOrgId ',
					FilterString: [{ "Left": "(", "FieldName": "FName", "Compare": "=", "Value": state.info.Data.Model.F_QUQY_ORGName, "Right": ")", "Logic": "and" }, { "Left": "(", "FieldName": "FUseOrgId", "Compare": "=", "Value": memberInfo.F_QUQY_COMPANY_Id, "Right": ")", "Logic": "and" }]
				}
			}).then(res => {
				if (res && res.length) {
					state.info.Data.Model.F_QUQY_ORGCUST.FNUMBER = res[0].FNUMBER
					state.info.Data.Model.F_QUQY_ORGCUSTName = res[0].FName
				}
			})
		}
		state.myInfo = uni.getStorageSync('myInfo')
		// 财务的话合并参数
		if (state.myInfo.role.includes(7)) Object.assign(state.info.Data.Model, state.Model2)
	})
</script>
<style lang="scss" scoped>
	.card {
		position: relative;
		width: calc(100% - 60rpx);
		margin: 20rpx auto;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		border-radius: 6rpx;

		.card-index {
			position: absolute;
			display: flex;
			// align-items: center;
			// justify-content: center;
			width: 40rpx;
			height: 40rpx;
			padding-left: 10rpx;
			font-size: 24rpx;
			background: #409eff;
			color: #fff;
			clip-path: polygon(0 0, 0 40rpx, 10rpx 40rpx, 40rpx 10rpx, 40rpx 0);
		}
	}
</style>